package com.hnx.admin.aurora.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

/*
创建人： 倔强的头发
创建时间：2025/6/14
功能描述:

*/
@Configuration
public class I18nConfig  implements WebMvcConfigurer {
    // 默认语言环境常量
    private static final Locale DEFAULT_LOCALE = Locale.CHINA;
    // 语言参数名常量
    private static final String LANGUAGE_PARAM_NAME = "lang";
    // Cookie名称
    private static final String COOKIE_NAME = "APP_LANGUAGE";
    // Cookie有效期(30天)
    private static final int COOKIE_MAX_AGE = (int) TimeUnit.DAYS.toSeconds(30);
    /**
     * 创建并配置LocaleResolver
     * 使用CookieLocaleResolver具有以下优势:
     * 1. 无状态，更适合分布式和微服务架构
     * 2. 减轻服务器内存压力
     * 3. 客户端持久化语言偏好
     */
    @Bean
    public LocaleResolver localeResolver()
    {
        CookieLocaleResolver localeResolver = new CookieLocaleResolver();
        localeResolver.setDefaultLocale(DEFAULT_LOCALE);
        localeResolver.setCookieName(COOKIE_NAME);
        localeResolver.setCookieMaxAge(COOKIE_MAX_AGE);
        // 设置Cookie HttpOnly和Secure标志增强安全性
        localeResolver.setCookieHttpOnly(true);
        // 生产环境应设置为true，此处注释以便开发测试
         localeResolver.setCookieSecure(true);
        return localeResolver;
    }
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor()
    {
        LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
        interceptor.setParamName(LANGUAGE_PARAM_NAME);
        // 设置忽略无效的Locale，防止恶意输入
        interceptor.setIgnoreInvalidLocale(true);
        return interceptor;
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor()).order(0); // 高优先级确保在其他拦截器前执行;
    }
}
